package org.example.jwt1.handler;


import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.jwt1.entity.ResponseResult;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.PrintWriter;

//无权限时的处理器
@Component
public class MyAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        ResponseResult sr = new ResponseResult<>();
        sr.setFlag(false);
        sr.setCode(3);
        sr.setErrorMsg("权限不足");
        ObjectMapper mapper = new ObjectMapper();
        String str = mapper.writeValueAsString(sr);
        out.write(str);
        out.close();
    }
//    @Override
//    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
//        httpServletResponse.setCharacterEncoding("UTF-8");
//        PrintWriter out = httpServletResponse.getWriter();
//        ResponseResult sr = new ResponseResult<>();
//        sr.setFlag(false);
//        sr.setCode(3);
//        sr.setErrorMsg("权限不足");
//        ObjectMapper mapper = new ObjectMapper();
//        String str = mapper.writeValueAsString(sr);
//        out.write(str);
//        out.close();
//    }
}

